# -*- coding:utf-8 -*-
import json

from django.http import HttpResponse


def render_json(dictionary={}):
    """
    return the json string for response
    @summary: dictionary也可以是string, list数据
    @note:  返回结果是个dict, 请注意默认数据格式:
                                    {'result': '',
                                     'message':''
                                    }
    """
    if type(dictionary) is not dict:
        # 如果参数不是dict,则组合成dict
        dictionary = {
            'result': True,
            'message': dictionary,
        }
    resp = HttpResponse(json.dumps(dictionary, ensure_ascii=False), content_type='application/json')
    return resp


# 成功返回数据
def success_result(data='', *args, **kwargs):
    result = {
        'result': True,
        'data': data
    }
    for arg in args:
        result = dict(result, **arg)
    result = dict(result, **kwargs)
    return render_json(result)


def response_result(resp):
    return render_json(resp)


# 失败返回数据
def fail_result(message='', *args, **kwargs):
    if not message:
        message = u'系统异常,请联系管理员'
    result = {
        'result': False,
        'message': message
    }
    for arg in args:
        result = dict(result, **arg)
    result = dict(result, **kwargs)
    return render_json(result)


# 成功返回数据
def success(data='', *args, **kwargs):
    result = {
        'result': True,
        'data': data
    }
    for arg in args:
        result = dict(result, **arg)
    result = dict(result, **kwargs)
    return result


# 失败返回数据
def failed(message='', *args, **kwargs):
    if not message:
        message = u'系统异常,请联系管理员'
    result = {
        'result': False,
        'message': message
    }
    for arg in args:
        result = dict(result, **arg)
    result = dict(result, **kwargs)
    return result
